<template>
  <div>
    <hmheader title="编辑资料">
      <span
        class="iconfont iconjiantou2"
        slot="left"
        @click="$router.back()"
      ></span>
      <span
        slot="right"
        class="van-icon van-icon-wap-home-o"
        @click="$router.push({ name: 'index' })"
      ></span>
    </hmheader>
    <div class="userImg">
      <img :src="userInfo.head_img" alt="" />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 昵称 -->
    <hmcell
      title="昵称"
      :desc="userInfo.nickname"
      @click="isShow.nickNameShow = !isShow.nickNameShow"
    ></hmcell>
    <!-- 不要将模态框中的输入框与单元格的Desc属性绑定为同一个数据属性，否则修改其中一个，另外一个也会变化 -->
    <van-dialog
      v-model="isShow.nickNameShow"
      title="标题"
      show-cancel-button
      @cancel="edituserInfo.nickname = userInfo.nickname"
      @confirm="updatenickName"
    >
      <van-field
        v-model="edituserInfo.nickname"
        required
        label="昵称"
        placeholder="请输入昵称"
      />
    </van-dialog>
    <!-- 密码 -->
    <hmcell
      title="密码"
      desc="******"
      @click="isShow.nickpwdShow = !isShow.nickpwdShow"
    ></hmcell>
    <van-dialog
      v-model="isShow.nickpwdShow"
      title="密码更改"
      show-cancel-button
      :beforeClose="beforeClose"
    >
      <van-field
        v-model="password.originpassword"
        required
        label="原密码"
        placeholder="请输入原密码"
      />
      <van-field
        v-model="password.newpassword"
        required
        label="新密码"
        placeholder="请输入新密码"
      />
    </van-dialog>
    <!-- 性别 -->
    <hmcell
      title="性别"
      :desc="userInfo.gender == 1 ? '男' : '女'"
      @click="isShow.nickGenderShow = !isShow.nickGenderShow"
    ></hmcell>
    <van-dialog
      v-model="isShow.nickGenderShow"
      title="性别更改"
      show-cancel-button
      @confirm="updategender"
      @cancel="edituserInfo.gender = userInfo.gender"
    >
      <van-picker
        title="性别更改"
        :columns="genderColumns"
        :default-index="userInfo.gender"
        @change="onChange"
      />
    </van-dialog>
  </div>
</template>

<script>
import hmheader from "@/components/hmheader.vue";
import hmcell from "@/components/hmcell.vue";
import { getUserById, updateUserInfo } from "@/apis/user.js";
import { uploadFile } from "@/apis/upload.js";
import axios from "@/utils/myaxios.js";
import { Toast } from "vant";
export default {
  components: {
    hmheader,
    hmcell,
  },
  data() {
    return {
      userInfo: {}, // 获取的用户信息，用于展示
      edituserInfo: {}, // 深拷贝一份用于修改编辑
      password: {
        originpassword: "",
        newpassword: "",
      },
      isShow: {
        nickNameShow: false,
        nickpwdShow: false,
        nickGenderShow: false,
      },
      genderColumns: ["女", "男"],
    };
  },
  async mounted() {
    // console.log(this.$route.params.id);
    let res = await getUserById(this.$route.params.id);
    console.log(res);
    if (res.data.message == "获取成功") {
      res.data.data.head_img = axios.defaults.baseURL + res.data.data.head_img;
      this.userInfo = res.data.data;
      this.edituserInfo = { ...this.userInfo };
    }
  },
  methods: {
    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file);
      let formdata = new FormData();
      formdata.append("file", file.file);
      let res = await uploadFile(formdata);
      // console.log(res);
      this.userInfo.head_img = axios.defaults.baseURL + res.data.data.url;
      if (res.data.message == "文件上传成功") {
        let res2 = await updateUserInfo(this.$route.params.id, {
          head_img: res.data.data.url,
        });
        console.log(res2);
        if (res2.data.message == "修改成功") {
          Toast.success("头像修改成功！");
        }
      }
    },
    async updatenickName() {
      let res = await updateUserInfo(this.$route.params.id, {
        nickname: this.edituserInfo.nickname,
      });
      console.log(res);
      if (res.data.message == "修改成功") {
        Toast.success("昵称修改成功！");
        this.userInfo.nickname = res.data.data.nickname;
      }
    },
    async updatepassword() {
      // let userpwd = JSON.parse(localStorage.getItem("hmtoutiao_pwd"));
      // console.log(userpwd);
      // if (userpwd.password != this.password.originpassword) {
      //   Toast.fail("原密码输入有误，请重新输入！");
      //   return;
      // }
      let res = await updateUserInfo(this.$route.params.id, {
        password: this.password.newpassword,
      });
      console.log(res);
      if (res.data.message == "修改成功") {
        Toast.success("密码修改成功！");
        let userpwd = JSON.parse(localStorage.getItem("hmtoutiao_pwd"));
        userpwd.password = this.password.newpassword;
        localStorage.setItem("hmtoutiao_pwd", JSON.stringify(userpwd));
      }
    },
    // 关闭模态框前触发-增加用户体验
    beforeClose(action, done) {
      let userpwd = JSON.parse(localStorage.getItem("hmtoutiao_pwd"));
      if (action == "confirm") {
        // 密码输入错误不关闭弹框
        if (userpwd.password != this.password.originpassword) {
          Toast.fail("原密码输入有误，请重新输入！");
          done(false);
        } else if (!/^\S{3,16}$/.test(this.password.newpassword)) {
          Toast.fail("请输入3-16位的密码！");
          done(false);
        } else {
          this.updatepassword();
          done();
        }
      } else {
        done();
      }
      this.password.originpassword = this.password.newpassword = "";
    },
    async updategender() {
      let res = await updateUserInfo(this.$route.params.id, {
        gender: this.edituserInfo.gender,
      });
      console.log(res);
      if (res.data.message == "修改成功") {
        this.userInfo.gender = res.data.data.gender;
      }
    },
    onChange(picker, value, index) {
      // console.log(`当前值：${value}, 当前索引：${index}`);
      // let g = value == "男" ? "1" : "0";
      // console.log(value, g);
      // this.edituserInfo.gender = g;
      this.edituserInfo.gender = index;
      // console.log(this.userInfo);
      // console.log(this.edituserInfo);
    },
  },
};
</script>

<style lang="less" scoped>
.userImg {
  position: relative;
  padding: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 70 * 100vw/360;
    height: 70 * 100vw/360;
    border-radius: 50%;
  }
}
// 调整引入的vant-uploader样式
// 在父组件中往往不能直接重置子组件中的元素样式，这个时候可以使用深度选择器来实现 >>> ：有兼容性问题；所以选择 /deep/
/deep/ .van-uploader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /deep/ .van-uploader__upload {
    opacity: 0;
    width: 70 * 100vw/360;
    height: 70 * 100vw/360;
    border-radius: 50%;
    margin: 0;
  }
}
.van-icon-wap-home-o {
  color: red;
}
</style>